<template>
    <div class="Invoice">
        <modal id="transaction-modal" :show.sync="showTransactionModal" :dialogCSS="{'width': '70%'}" @submit="genNewInvoice">
            <template slot="header">
                Add Transactions
            </template>
            <template slot="body">
                <div>
                    <table class="table" cellspacing="14" style="width: 100%;">
                        <thead>
                            <tr>
                                <th>amount</th>
                                <th>currency</th>
                                <th>comment</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr  :key="'transaction' + index" class="advance-table-row active" v-for="(item, index) in transactionData">
                                <td>
                                    {{item.amount}}
                                </td>
                                <td>
                                    {{item.currency}}
                                </td>
                                <td>
                                    {{item.comment}}
                                </td>
                            </tr>
                            <tr class="advance-table-row">
                                <td>
                                    <input type="number" class="form-control" v-model="transaction.amount">
                                </td>
                                <td>
                                    <select class="form-control" v-model="transaction.currency">
                                        <option  :key="'currency' + index" v-for="(currency, index) in currencies" :value="currency">{{currency}}</option>
                                    </select>
                                </td>
                                <td>
                                    <input type="text" class="form-control" v-model="transaction.comment">
                                </td>
                            </tr>
                        </tbody>
                    </table>
                    <div style="text-align: center">
                        <div style="border: 2px solid rgba(120, 130, 140, .13)" class="p-10">
                            <button class="btn btn-success btn-circle" @click="addTransaction">
                                <i class="fif fif-plus"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </template>
        </modal>
        <modal id="send-detail" :show.sync="sendDetailModal"  :height="600">
            <template slot="header">
                Sending Result
            </template>
            <template slot="body">
                <div class="p-20">
                    <ul class="nav">
                        <li :key="'send' + host_name" class="clearfix p-b-10" v-for="(item, host_name) in sendList" style="border-bottom: 1px solid #eee">
                            <span>{{host_name}}</span>
                            <span class="p-l-10 text-info" v-if="!item.done">Sending...</span>
                            <span class="p-l-10 text-success" v-if="item.done">Done</span>
                            <span class="pull-right text-success" v-if="item.error && !item.error.code"><i class="fif fif-check"></i></span>
                            <span class="pull-right text-danger" v-if="item.error && item.error.code"><i class="fif fif-close"></i></span>
                            <div class="text-danger p-l-30" v-if="item.error && item.error.code && item.error.msg.length">
                                {{item.error.msg}}
                            </div>
                        </li>
                    </ul>
                </div>
            </template>
            <template slot="footer">
                <button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Close</button>
            </template>
        </modal>
        <ItemDetail :show.sync="showModal" :value="item" :title="`${action} Item`" :id="itemID" @submit="confirmSubmit"
                    :action="action" ></ItemDetail>
        <div class="row">
            <div class="col-md-12 p-0">
                <filter-form v-if="filters.length" :columns="filters" @submit="submit"></filter-form>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12 p-0">
                <div class="panel">
                    <div class="panel-heading" style="overflow: hidden;">
                        Generate Invoice
                        <button class="btn btn-warning pull-right" @click="sendDetailModal = true">Result</button>
                    </div>
                    <div class="input-group m-b-30" style="padding: 0 20px 20px 20px;">
                        <date-button :range="true" :defaultToNow="true" v-model="date"></date-button>
                        <span class="input-group-btn">
                              <button class="btn btn-info" type="button" @click="genInvoice" :disabled="tableLoading">Generate!</button>
                        </span>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12 bg-white p-0 m-0">
                <item-table title="Invoice List" :columns="defaultColumns" :data="data" :loading="tableLoading" @sort="sort"
                            :total="total" :pageSize="pageSize" :model="model" isColumns multipie :batchButtons="batchButtons" @batch="_batch"
                            isExport @export="exportExcel"
                >
                    <template slot="is_invalid" slot-scope="props">
                        <span class="label label-success" v-if="props.item.is_invalid">YES</span>
                        <span class="label label-danger" v-else>
                            NO
                        </span>
                    </template>
                    <template slot="is_paid" slot-scope="props">
                        <span class="label label-success" v-if="props.item.is_paid">YES</span>
                        <span class="label label-danger" v-else>
                            NO
                        </span>
                    </template>
                    <template slot="actions" slot-scope="props">
                        <button type="button" class="btn btn-danger btn-outline btn-circle btn-md m-r-5" @click="cancel(props)">
                            <i class="fif fif-invalid"></i>
                        </button>
                    </template>
                </item-table>
                <v-paginate :pageCount="pageCount" :page="page" @change="changePage"></v-paginate>
            </div>
        </div>
    </div>
</template>

<script>
    // components
    import vSelect from 'vue-select'
    import vPaginate from '@/components/widgets/Pagination'
    import ItemTable from '@/components/widgets/ItemTable'
    import ItemDetail from '@/components/widgets/ItemDetail'
    import FilterForm from '@/components/widgets/FilterForm'
    import Modal from '@/components/widgets/Modal'
    import DateButton from '@/components/widgets/Datepicker/DateButton'

    // utlis
    import {toJsonData} from '@/utils'
    // mixin
    import {lifeHookMixin, itemMixin} from '@/mixins/item'
    // config
    import config from '@/config'
    // api
    import {invalidateInvoice, makeInvoice, sendInvoice} from "@/api/bill"

    import swal from 'sweetalert'

    export default {
        name: "Invoice",
        components: {vSelect, vPaginate, ItemTable, FilterForm, ItemDetail, Modal, DateButton},
        mixins: [lifeHookMixin, itemMixin],
        created() {
            this.currencies = config.CURRENCY
            this.batchButtons = [{
                label: 'Send',
                cls: 'btn-info'
            }]
        },
        data() {
            return {
                // transaction
                showTransactionModal: false,
                sendDetailModal: false,
                transaction: {
                    currency: 'JPY'
                },
                transactionData: [],
                currentInvoice: null,
                date: '',
                pageSize: 100,

                sendList: {}
            }
        },
        methods: {
            addTransaction() {
                if (this.transaction.amount.trim()) {
                   // this.transaction.fee_type = 3
                    this.transaction.amount = parseFloat(this.transaction.amount)
                    this.transactionData.push(this.transaction)
                    this.$nextTick( () => {
                        this.transaction = {
                            currency: 'JPY'
                        }
                    } )
                }
            },
            _batch(selected) {
                if (selected.length === 1 && selected[0].is_invalid) {
                    return $.toast({
                        heading: 'this invoice is invalid',
                        position: 'top-right',
                        loaderBg: '#ff6849',
                        icon: 'error',
                    })
                }

                for (let i=0; i<selected.length; i++) {
                    if (selected[i].is_invalid) {
                        selected.splice(i, 1)
                        i--
                    }
                }

                this.sendDetailModal = selected.length ? true : false
                if (!this.tableLoading) {
                    this.sendList = {}
                    this.tableLoading = selected.length ? true : false
                    for (let i=0; i<selected.length; i++) {
                        let item = selected[i]

                        if (item.is_invalid) break;

                        let tmp = {
                            id : item.id,
                            host_name: item.host__host_name,
                            done: false
                        }
                        this.$set(this.sendList, item.host__host_name, tmp)
                        this.sendList[item.host__host_name] = tmp
                        sendInvoice({invoices: [item.id]}).then( res => {
                            this.markDone(res.data)
                        } ).catch( e => {
                            // network error
                            let data = {}
                            data[item.host__host_name] = {
                                code: 1,
                                msg: e.message
                            }
                            this.markDone(data)
                        } )
                    }
                }

            },
            markDone(data) {
                for (let host_name in data) {
                    this.sendList[host_name].done = true
                    this.sendList[host_name].error = {
                        code: data[host_name].code,
                        msg: data[host_name].msg,
                    }
                }

                // to test whether all done
                let allDone = true
                for (let host_name in this.sendList) {
                    if (!this.sendList[host_name].done) {
                        allDone = false
                        break;
                    }
                }
                if (allDone) {
                    this.tableLoading = false
                    this.fetch()
                }

            },
            cancel(props) {
                this.transactionData = []
                this.showTransactionModal = true
                this.currentInvoice = props.item
            },
            genNewInvoice() {
                if (this.transactionData.length) {
                    invalidateInvoice({
                        invoice_id: this.currentInvoice.id,
                        transactions: this.transactionData
                    }).then( res => {
                        this.fetch()
                        this.showTransactionModal = false
                    } ).then( e => {

                    } )
                } else {
                    return $.toast({
                        heading: 'Add some transactions',
                        position: 'top-right',
                        loaderBg: '#ff6849',
                        icon: 'error',
                    })
                }
            },
            genInvoice() {
                let arr = this.date.split('/')
                let start = arr[0]
                let end = arr[1]
                swal({
                    title: "Are you sure?",
                    text: `Generate ${this.date} Invoice`,
                    icon: "warning",
                    dangerMode: true,
                    buttons: true,
                }).then((willDelete) => {
                    if (willDelete) {
                        this.tableLoading = true
                        makeInvoice({start, end}).then(res => {
                            this.tableLoading = false
                            swal("success", "", "success")
                            this.fetch()
                        }).catch(e => {
                            this.tableLoading = false
                        })
                    }
                })
            }
        },
    }
</script>

<style scoped>

</style>